<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------
// | 登录重写 By ganjn <higjn@163.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\model\Admin;
use think\Db;
use \think\Cache;
use \think\Controller;
use \think\Session;

class Common extends Controller
{
    /**
     * 清除全部缓存
     * @return [type] [description]
     */
    public function clear()
    {
        if (!Cache::clear()) {
            return $this->error('清除缓存失败');
        }
        return $this->success('清除缓存成功');
    }



    /**
     * 登录重写
     * @author ganjn <higjn@163.com>
     * @return [type] [description]
     */
    public function login()
    {
        // 已登录直接跳转
        if (Session::has('user')) {
            return $this->redirect('admin/index/index');
        }

        if ($this->request->isPost()) {
            // 数据
            $data = $this->request->post();

            $verifycode = $data['captcha'];

            //验证验证码
            if(!captcha_check($verifycode)){
                return $this->error('验证码错误');
            }

            $admin = new Admin();

            $list = $admin->where(['account'=>$data['name']])->find();

            if (empty($list) || md5($data['password']) != $list['password']) {
                return $this->error('用户名或密码错误');
            }

            Session::set('user', $list);

            return $this->success('登录成功,正在跳转...', 'admin/index/index');
        }

        return $this->fetch();
    }

    /**
     * 管理员退出，清除名字为admin的session
     * @return [type] [description]
     */
    public function logout()
    {
        Session::clear();
        session_destroy();
        if (Session::has('user')) {
            return $this->error('退出失败');
        }

        return $this->success('正在退出...', 'admin/common/login');
    }
}
